package com.ybear.ybnetworkutil.network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import androidx.annotation.NonNull;

import com.ybear.ybnetworkutil.annotations.NetworkType;

/**
 * 网络工具类
 */
public class NetworkUtil {
    public static ConnectivityManager getConnectivityManager(@NonNull Context context) {
        return (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public static boolean isWifi(@NonNull Context context) {
        ConnectivityManager manager = getConnectivityManager( context );
        if( manager == null ) return false;
        NetworkInfo info = manager.getNetworkInfo( ConnectivityManager.TYPE_WIFI );
        // 返回网络连接状态
        return info != null && info.isConnected();
    }

    public static boolean isMobile(@NonNull Context context) {
        ConnectivityManager manager = getConnectivityManager( context );
        if( manager == null ) return false;
        NetworkInfo info = manager.getNetworkInfo( ConnectivityManager.TYPE_MOBILE );
        // 返回网络连接状态
        return info != null && info.isConnected();
    }

    /**
     * 获取当前网络状态
     * @param context   上下文
     * @return          网络是否可用
     */
    public static boolean isNetwork(@NonNull Context context) {
        return isMobile( context ) || isWifi( context );
    }

    @NetworkType
    public static String getNetworkStatus(@NonNull Context context) {
        if( isWifi( context ) ) return NetworkType.WIFI;
        if( isMobile( context ) ) return NetworkType.MOBILE;
        return NetworkType.NONE;
    }
}
